<template>
  <div class="login-container">
    <div class="login-header">
      <h1 class="system-title">康管家家庭健康管家平台</h1>
    </div>

    <div class="login-form">
      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="loginForm.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          <van-field
            v-model="loginForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码长度不能小于6位' }
            ]"
          />
        </van-cell-group>

        <div class="submit-btn">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            登录
          </van-button>
        </div>
      </van-form>

      <div class="register-link">
        <span>还没有账号？</span>
        <router-link to="/register">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loginForm = ref({
  username: '',
  password: ''
})

const loading = ref(false)

const handleLogin = async () => {
  try {
    loading.value = true
    const data = await userStore.userLogin(loginForm.value)
    showToast('登录成功')

    // 根据角色跳转到不同页面
    if (data.userInfo.roleId === 2) {
      router.replace('/doctor')
    } else {
      router.replace('/home')
    }
  } catch (error) {
    showToast(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  //display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;

  .login-header {
    text-align: center;
    margin: 40px 0;

    .system-title {
      font-size: 24px;
      color: #323233;
      margin-bottom: 10px;
    }

    .system-desc {
      font-size: 14px;
      color: #969799;
    }
  }

  .login-form {
    width: 100%;
    max-width: 400px;

    .submit-btn {
      margin-top: 24px;
      padding: 0 16px;
    }

    .register-link {
      margin-top: 15px;
      text-align: center;
      color: #666;
      font-size: 15px;
      a {
        color: #1989fa;
        margin-left: 4px;
      }
    }
  }
}

// 响应式布局
@media screen and (min-width: 768px) {
  .login-container {
    justify-content: center;

    .login-header {
      .system-title {
        font-size: 32px;
      }

      .system-desc {
        font-size: 16px;
      }
    }
  }
}
</style>
